<template>
  <div class="logo-content">
    <div class="logo-left">
      <div class="title">AI检测平台</div>
      <div class="header">
        <div class="image-logo">
          <el-image :src="loginImg" fit="contain" class="img"></el-image>
        </div>
      </div>
      <a class="yuming" href="https://beian.miit.gov.cn/" target="_blank">
        <!-- Copyright©2020X0000X有限公司 -->
      </a>
    </div>
    <div class="login-container">
      <el-form :model="loginForm" :rules="loginRules" auto-complete="on" class="login-form" label-position="left"
        ref="loginFormRef">
        <div class="logo">LOGO</div>
        <div class="title-container mb-30">
          <h3 class="title">
            欢迎使用<span class="text">AI检测平台管理系统</span>
          </h3>
        </div>
        <el-form-item prop="username" :rules="loginRules">
          <!-- <span class="svg-container"> -->
          <!-- <svg-icon icon-class="user" /> -->
          <!-- </span> -->
          <el-icon class="svg-container">
            <UserFilled />
          </el-icon>
          <el-input auto-complete="on" name="username" placeholder="请输入账号" ref="username" tabindex="1" type="text"
            v-model="loginForm.username" clearable />
        </el-form-item>

        <el-form-item prop="password">
          <!-- <span class="svg-container">
            <svg-icon icon-class="password" />
          </span> -->
          <el-icon class="svg-container">
            <Lock />
          </el-icon>
          <el-input :key="passwordType" :type="passwordType" @keyup.enter.native="handleLogin" auto-complete="on"
            name="password" placeholder="请输入密码" ref="passwordRef" tabindex="2" v-model="loginForm.password" clearable />
          <span @click="showPwd" class="show-pwd">
            <el-icon class="svg-container">
              <View v-if="passwordType === 'password'" />
              <Hide v-else />
            </el-icon>
            <!-- <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            /> -->
          </span>
        </el-form-item>
        <el-form-item prop="captcha" class="yanzhengma">
          <div class="captcha-content">
            <el-input @keyup.enter.native="handleLogin" auto-complete="on" name="captcha" placeholder="请输入验证码"
              ref="captcha" tabindex="3" type="text" v-model="loginForm.captcha" class="captcha-input" clearable />
            <div class="captcha-img" @click="getVerificationCode">
              <img :src="verificationImg" class="img" />
            </div>
          </div>
        </el-form-item>

        <el-button :loading="loading" @click.native.prevent="handleLogin" class="btnLand" type="primary">登录</el-button>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  computed,
  watch,
  onMounted,
  onBeforeUnmount,
  reactive,
  shallowRef,
  onUnmounted,
  nextTick,
} from "vue";
import { verificationCode } from "@/api/user.js";
import { ElMessageBox, ElMessage } from "element-plus";
import { useStore } from "vuex";
const store = useStore();
import { useRoute, useRouter } from "vue-router";

const loginForm = reactive({
  username: "",
  password: "",
  captcha: "",
  checkKey: "",
});

let loginFormRef: any = ref(null);
let passwordRef: any = ref(null);
let loginRules: any = reactive({
  username: [
    {
      required: true,
      trigger: "blur",
      message: "请正确输入账号",
    },
  ],
  password: [
    {
      required: true,
      trigger: "blur",
      message: "请正确输入密码",
    },
  ],
  captcha: [
    {
      required: true,
      trigger: "blur",
      message: "请正确验证码",
    },
  ],
});
let loading = ref(false);
let passwordType = ref("password");
let redirect: any = ref(null);
let verificationImg = ref("");
let loginImg = new URL("@/assets/indexLog.png", import.meta.url).href;
const router = useRouter();
const route = useRoute();
watch(
  () => route,
  (newPath, oldPath) => {
    redirect.value = route.query && route.query.redirect;
  },
  { deep: true, immediate: true }
);
onMounted(() => {
  getVerificationCode();
});

onBeforeUnmount(() => { });
onUnmounted(() => { });
// 验证码
const getVerificationCode = async () => {
  let key = randomCoding();
  loginForm.checkKey = key;
  let res = await verificationCode({}, key);
  console.log("验证码", res);

  if (res.success) {
    verificationImg.value = res?.data?.result;
    loginForm.captcha = "";
  } else {
    ElMessage({
      message: "获取验证码失败",
      type: "error",
    });
  }
};
const randomCoding = () => {
  var arr = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
  ];
  var idvalue = "";
  let n = 5; // 对应的生成多少个字母
  for (var i = 0; i < n; i++) {
    idvalue += arr[Math.floor(Math.random() * 26)];
  }
  return idvalue;
};
const showPwd = () => {
  passwordType.value = passwordType.value === "password" ? "" : "password";
  nextTick(() => {
    passwordRef.value && passwordRef.value.focus();
  });
};
const handleLogin = () => {
  console.log('路径', redirect.value);

  try {
    if (loginForm.password && loginForm.captcha && loginForm.username) {
      nextTick(() => {
        loginFormRef.value.clearValidate();
      });
      loading.value = true;
      store
        .dispatch("login", loginForm)
        .then((res) => {
          ElMessage({
            message: res?.message || "登录成功",
            type: "success",
          });
          router.push({
            path: redirect.value || "/",
          });
          loading.value = false;
        })
        .catch((err) => {
          ElMessage({
            message: err?.data?.message || "登录失败",
            type: "error",
          });
          getVerificationCode();
          loading.value = false;
        });
    } else {
      ElMessage({
        message: "请填写完整",
        type: "error",
      });
    }
  } catch (err) {
    loginFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        store
          .dispatch("login", loginForm)
          .then((res) => {
            ElMessage({
              message: res?.message || "登录成功",
              type: "success",
            });
            router.push({
              path: redirect.value || "/",
            });
            loading.value = false;
          })
          .catch((err) => {
            ElMessage({
              message: err?.data?.message || "登录失败",
              type: "error",
            });
            getVerificationCode();
            loading.value = false;
          });
      } else {
        return false;
      }
    });
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    // color: $cursor;
    color: #000;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      // padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      // caret-color: $cursor;
      color: #000;
      // &:-webkit-autofill {
      //   box-shadow: 0 0 0px 1000px $bg inset !important;
      //   -webkit-text-fill-color: $cursor !important;
      // }
    }
  }

  .el-form-item {
    border-radius: 60px;
    background-color: rgba(245, 245, 245, 100);
    color: rgba(204, 204, 204, 100);
    font-size: 16px;
    text-align: center;
    font-family: Microsoft Yahei;
    margin-bottom: 40px;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.logo-content {
  width: 100%;
  height: 100%;
  overflow: auto;
  display: grid;
  grid-template-columns: 1.4fr 1fr;

  .logo-left {
    position: relative;
    height: 100%;
    width: 100%;
    background-color: rgb(58, 98, 215);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;

    .title {
      text-align: center;
      color: rgba(255, 255, 255, 100);
      font-size: 36px;
      text-align: center;
      font-family: SourceHanSansSC-regular;
      padding-top: 6%;
    }

    .header {

      // display: flex;
      // flex-direction: column;
      // align-items: center;
      .image-logo {
        width: 560px;
        height: 520px;
        border-radius: 50%;
        overflow: hidden;
        display: flex;
        justify-content: center;

        .img {
          width: 84%;
          height: 100%;
        }
      }
    }

    .yuming {
      // align-self: center;
      color: #fff;
    }
  }

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;

    .logo {
      color: rgba(58, 98, 215, 100);
      font-size: 28px;
      text-align: left;
      font-family: SourceHanSansSC-regular;
      font-weight: 550;
    }

    .login-form {
      position: relative;
      width: 450px;
      max-width: 100%;
      padding: 0 35px;
      margin: 0 auto;
      overflow: hidden;
    }

    .svg-container {
      color: $dark_gray;
      width: 40px;
      display: inline-block;
      font-size: 22px;
      padding-left: 4px;
    }

    .title-container {
      position: relative;
      padding-top: 1.25rem;

      .title {
        font-weight: 500;
        color: rgba(16, 16, 16, 100);
        font-size: 28px;
        text-align: left;
        font-family: SourceHanSansSC-regular;

        .text {
          color: #3a62d7;
        }
      }
    }

    .show-pwd {
      position: absolute;
      right: 15px;
      top: 12px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .btnLand {
      width: 100%;
      display: block;
      margin: 0 auto;
      border-radius: 50px;
      background-image: linear-gradient(to right, #2ac5f3, #38b2f8, #45a0fd);
    }
  }

  .captcha-content {
    display: grid;
    grid-template-columns: 1fr 1fr;
    background-color: #fff;

    .captcha-input {
      background-color: whitesmoke;
      width: 100%;
      border-radius: 4px;
      margin-left: 10px;
    }

    .captcha-img {
      width: 100%;
      height: 47px;
      margin-left: 10px;
      border-radius: 4px;

      // background-color: red;
      .img {
        width: 75%;
        height: 100%;
      }
    }
  }

  :deep(.el-input__wrapper) {
    display: flex;
    background-color: #f5f5f5;
    box-shadow: none;
    // margin: -10px 0 0;
    font-size: 1em;
    border-radius: 0;
    --el-input-text-color: #bcbcbc;
    border-collapse: collapse;
    padding: 0 2px;
  }

  :deep(.yanzhengma) {
    background-color: #fff;
  }

  :deep(.yanzhengma .el-input__wrapper) {
    padding: 0 10px;
  }
}
</style>
